import router from '@/router'
import axios from 'axios'
import { Message } from 'element-ui'
import { Loading } from 'element-ui'
const service = axios.create({
  baseURL: '/api',
  timeout: 5000 // request timeout
})

// 请求拦截器
service.interceptors.request.use(

  config => {
    if (config.url !== '/login') {
      if (localStorage.getItem('token') === null) {
        router.push('/login')
        Message.error('登录过期，请重新登录')
      }
    }
    config.headers.Authorization = 'Bearer ' + localStorage.getItem('token')
    const options = {
      lock: true,
      text: '加载中...',
      background: '(122, 122, 122, 0.8)'
    }
    Loading.service(options)
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => {
    const options = {
      lock: true,
      text: '加载中...',
      background: '(122, 122, 122, 0.8)'
    }
    Loading.service(options).close()
    return response.data
  },
  error => {
    const options = {
      lock: true,
      text: '加载中...',
      background: '(122, 122, 122, 0.8)'
    }
    Loading.service(options).close()
    if (error.response.status === 401) {
      router.push('/login')
      Message.error('登录过期')
    }
    return Promise.reject(error)
  }
)

export default service
